package com.epfresh.supplier.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.OrderOnGroupActivity;
import com.epfresh.supplier.activity.OrderOnGroupMinusDetailActivity;
import com.epfresh.supplier.activity.ReturnApplicationInfoActivity;
import com.epfresh.supplier.adapter.OrderOnGroupMinusAdapter;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.OrderOnGroupMinus;
import com.epfresh.supplier.entity.StatusEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zzq on 2017/9/14.
 */
public class OrderOnGroupMinusFragment extends OrderOnGroupFragment implements LoadMoreListView.IXListViewListener {
    //待支付 2待发货 3 待收货 4 拒签（不显示） 5退款 6 交易取消 7 交易成功 9 待评价 10减免退
    boolean typeFlag;//订单类别展示开关
    //订单列表类别 1,待支付 2,未完成,3已完成 4全部订单
    public int typeState;
    //0线上,1线下,2现场，当前暂时默认现场等同线下

    private LoadMoreListView lvContent;

    private List<OrderOnGroupMinus> list = new ArrayList<>();

    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    public int requestSucceedCount = 0;
    private int PAGE_SIZE = 5;
    public OrderOnGroupMinusAdapter adapter;
    Context context;
    OrderOnGroupActivity baseActivity;
    TagPager tagPager = new TagPager();
    @Override
    public String getBaseTag() {
        return Constant.TAG_ORDER_FRAGMENT;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_order,
                container, false);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        //super.onViewCreated(v, savedInstanceState);
        context = getContext();
        baseActivity = (OrderOnGroupActivity)getAppActivity();
        initHeadView(v);
        lvContent = (LoadMoreListView)v.findViewById(R.id.lv_content);

        vException = v.findViewById(R.id.v_exception);
        mainView = v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
        adapter = new OrderOnGroupMinusAdapter(context,lvContent, list);
        adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
                Log.e("new onItemClick",""+position);

// 交货码，查看物流，取消订单，确认收货，支付， 详情
                switch (v.getId()) {
                    case R.id.tv_item_order_on_group_minus_cancel:
                        requestCancel(list.get(position).getId());
                        break;
                    case R.id.tv_item_order_on_group_minus_again:
                        Intent intent = new Intent(context, ReturnApplicationInfoActivity.class);
                        intent.putExtra("jmtId", list.get(position).getId());
                        startActivityForResult(intent, 0x002);//2，减免退；3，支付；
                        //context.startActivity(intent);
                        break;
                    case R.id.tv_item_order_on_group_minus_detail:
                        Intent detail = new Intent(context, OrderOnGroupMinusDetailActivity.class);
                        detail.putExtra("id", list.get(position).getId());
                        startActivity(detail);
                        break;
                }
            }
        });

        lvContent.setAdapter(adapter);
        lvContent.setXListViewListener(this);
        loadData(0);
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvContent, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    boolean refreshFlag = false;

    public void refresh() {
        if(lvContent==null)
            return;
        lvContent.resetNoMore();
        requestSucceedCount = 0;
        refreshFlag = true;
        loadData(0);
        baseActivity.requestOrderInfo();
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        //loadData(type, number + 1);
        loadData(number + 1);
    }

    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            lvContent.noMore();
        } else {
            lvContent.stopLoadMore();
        }
    }



    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }


    public void loadData(int page){
        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        Map<String, String> map = new HashMap<>();
        map.put("buyerStoreId", BaseApplication.getInstance().getStoreId());
        map.put("pageNumber", page + "");
        map.put("pageSize", PAGE_SIZE + "");
        map.put("orderStage", "60");
        map.put("keyword","");
        entity.setCmd("pm-order/baseorder/order/list");
        entity.setParameters(map);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = "pm-order/baseorder/order/list";
        requestTag.action = page;
        requestTag.type = RequestTag.TYPE_CURRENT;
        request(entity, requestTag, onRequestListener);
    }

    OnRequestListener<ContentEntity<OrderOnGroupMinus>> onRequestListener = new OnRequestListener<ContentEntity<OrderOnGroupMinus>>() {
        @Override
        public ContentEntity<OrderOnGroupMinus> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<OrderOnGroupMinus>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.nostandingbook, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.nostandingbook, arg + "", HttpRequest.FAIL_NET_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0 && !refreshFlag){
                showProgressView();
            }else
                refreshFlag = false;
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<OrderOnGroupMinus>> response, Object tag) {
            //页面第一次调用网络请求接口并成功
            showMainView();
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0||requestSucceedCount==0) {
                list.clear();
            }
            requestSucceedCount ++;

            ContentEntity<OrderOnGroupMinus> orderResponse = response.getResponseElement();
            List<OrderOnGroupMinus> content = orderResponse.getContent();
            tagPager.setLast(orderResponse.getLast());
            tagPager.setNumber(orderResponse.getNumber());
            tagPager.setSize(orderResponse.getSize());
            tagPager.setTotalElements(orderResponse.getTotalElements());
            list.addAll(content);
            adapter.notifyDataSetChanged();
            if(orderResponse.getNumber()==0){
                    lvContent.setSelection(0);
            }
            updateViewStatus(requestTag);
            if(list.size()==0){
                showExceptionView(R.mipmap.nostandingbook, "没有相关的拼货", HttpRequest.FAIL_DATA_EMPTY);
            }
        }
    };



    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    void requestCancel(String id){
        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        Map<String, String> map = new HashMap<>();
        map.put("orderJmtId", id);
        entity.setCmd("pm-order/baseorder/order/jmt/cancelApply");
        entity.setParameters(map);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = "pm-order/baseorder/order/jmt/cancelApply";
        request(entity, requestTag, onRequestCancelListener);
    }

    OnRequestListener<StatusEntity> onRequestCancelListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            T.toast("请求失败，请重试");
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            T.toast("请求失败，请重试");
            hideProgressDialog();

        }

        @Override
        public void onStart(Object tag) {
            //showProgressView();
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            //页面第一次调用网络请求接口并成功
            hideProgressDialog();
            StatusEntity orderResponse = response.getResponseElement();
            if(orderResponse.isSuccess()){
                list.remove(postionFlag);
                adapter.notifyDataSetChanged();
            }else{
                T.toast("取消失败，请联系客服");
            }
        }
    };

}
